//package com.hjb.service.controller.recharge;
//
//import java.math.BigDecimal;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.servlet.ModelAndView;
//
//import com.hjb.service.config.properties.FuiouProperties;
//import com.hjb.service.domain.product.SiteUserBuy;
//import com.hjb.service.domain.recharge.SiteUserRecharge;
//import com.hjb.service.domain.recharge.SiteUserRechargeExample1;
//import com.hjb.service.domain.siteuser.SiteUser;
//import com.hjb.service.domain.siteuseraccount.SiteUserAccount;
//import com.hjb.service.domain.siteuseraccount.SiteUserAccountExample;
//import com.hjb.service.gateway.fuiou.DESCoderFUIOU;
//import com.hjb.service.gateway.fuiou.FyPayConstant;
//import com.hjb.service.gateway.fuiou.FyPayInfo;
//import com.hjb.service.gateway.fuiou.FyPayReturnInfo;
//import com.hjb.service.gateway.fuiou.FyPayUtils;
//import com.hjb.service.gateway.fuiou.MD5;
//import com.hjb.service.mapper.SiteUserAccountMapper;
//import com.hjb.service.mapper.SiteUserRechargeMapper;
//import com.hjb.service.recharge.FYRechargeService;
//import com.hjb.service.utils.MapUtil;
//
///**
// * Created by gy on 2017/7/28.
// * 充值
// */
//@RestController
//@RequestMapping("/fyrecharge")
//public class FYRechargeController {
//	private Logger log = LoggerFactory.getLogger(getClass());
//
//	@Autowired
//	private FYRechargeService fyRechargeService;
//	@Autowired
//	private FuiouProperties fuiouProperties;
//	@Autowired
//	private SiteUserRechargeMapper siteUserRechargeMapper;
//	@Autowired
//	private SiteUserAccountMapper siteUserAccountMapper;
//
//	/**
//	 * 用户充值
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping("/recharge")
//	@ResponseBody
//	public Map<String, Object> recharge(HttpServletRequest request) {
//		Map<String, Object> resMap = new HashMap<String, Object>();
//		try {
//			String amount = request.getParameter("amount");//new BigDecimal("10")
//			String orderId = request.getParameter("orderId");//String.valueOf(System.currentTimeMillis()+siteUserBuy.getUserId())
//
//			SiteUser siteUser = (SiteUser) request.getSession().getAttribute("siteUser");
//			if (siteUser == null){
//				resMap.put("result_code",MapUtil.INTF_ERR_CODE_416);
//				resMap.put("result_info", "获取验证码失败，请重新登录");
//				return resMap;
//			}
//			Integer userId = siteUser.getUserId();
//			if (!siteUser.getUserId().equals(userId)){
//				resMap.put("result_code",MapUtil.INTF_ERR_CODE_416);
//				resMap.put("result_info", "获取验证码失败，请重新登录");
//				return resMap;
//			}
//
//			FyPayInfo fyPayInfo = new FyPayInfo();
//			// 构造支付请求对象
//			fyPayInfo.setMchnt_cd(FyPayUtils.nvl(fuiouProperties.getMerchId()));
//			fyPayInfo.setOrder_id(FyPayUtils.nvl(orderId));
//			// 富友传参数金额以分为单位
//			BigDecimal amout = new BigDecimal(amount).multiply(new BigDecimal(100));
//			fyPayInfo.setOrder_amt(amout.setScale(0));
//			fyPayInfo.setUser_type(FyPayConstant.FyPayType.manage.getV());
//			fyPayInfo.setCert_type(FyPayConstant.CertType.IDCARD);
//			fyPayInfo.setUser_id((long)userId);
//			fyPayInfo.setBack_notify_url(FyPayUtils.nvl(fuiouProperties.getReturnUrl()));
//			// 支付info
//			fyPayInfo.setCard_no(FyPayUtils.nvl(siteUser.getBankCardNo()));
//			fyPayInfo.setCert_no(FyPayUtils.nvl(siteUser.getCardNumber()));
//			fyPayInfo.setCardholder_name(FyPayUtils.nvl(siteUser.getName()));
//			fyPayInfo.setPage_notify_url(fuiouProperties.getNotifyUrl());
//			fyPayInfo.setPage_notify_url_err(fuiouProperties.getNotifyErrUrl());
//			// RSA加签字符串
//			StringBuffer sb = new StringBuffer();
//			sb.append(fuiouProperties.getPayType()).append("|").
//					append(fuiouProperties.getVersion()).append("|").
//					append(fyPayInfo.getMchnt_cd()).append("|").
//					append(fyPayInfo.getOrder_id()).append("|").
//					append(fyPayInfo.getUser_id()).append("|").
//					append(fyPayInfo.getOrder_amt()).append("|").
//					append(fyPayInfo.getCard_no()).append("|").
//					append(fuiouProperties.getReturnUrl()).append("|").
//					append(fyPayInfo.getCardholder_name()).append("|").
//					append(fyPayInfo.getCert_no()).append("|").
//					append(fyPayInfo.getCert_type()).append("|").
//					append(fuiouProperties.getLogoTp()).append("|").
//					append(fyPayInfo.getPage_notify_url()).append("|").
//					append(fyPayInfo.getPage_notify_url_err()).append("|").append(fuiouProperties.getMd5Key());
//
//			log.info("app pay 签名前："+sb.toString());
//			String signStr = MD5.MD5Encode(sb.toString());
//			log.info("app pay 签名后："+signStr);
//
//			StringBuffer sbFm = new StringBuffer();
//			sbFm.append("<ORDER>");
//			sbFm.append("<VERSION>").append(fuiouProperties.getVersion()).append("</VERSION>");
//			sbFm.append("<LOGOTP>").append(fuiouProperties.getLogoTp()).append("</LOGOTP>");
//			sbFm.append("<MCHNTCD>").append(fyPayInfo.getMchnt_cd()).append("</MCHNTCD>");
//			sbFm.append("<TYPE>").append(fuiouProperties.getPayType()).append("</TYPE>");
//			sbFm.append("<MCHNTORDERID>").append(fyPayInfo.getOrder_id()).append("</MCHNTORDERID>");
//			sbFm.append("<USERID>").append(fyPayInfo.getUser_id()).append("</USERID>");
//			sbFm.append("<AMT>").append(fyPayInfo.getOrder_amt()).append("</AMT>");
//			sbFm.append("<BANKCARD>").append(fyPayInfo.getCard_no()).append("</BANKCARD>");
//			sbFm.append("<NAME>").append(fyPayInfo.getCardholder_name()).append("</NAME>");
//			sbFm.append("<IDTYPE>").append(fyPayInfo.getCert_type()).append("</IDTYPE>");
//			sbFm.append("<IDNO>").append(fyPayInfo.getCert_no()).append("</IDNO>");
//			sbFm.append("<BACKURL>").append(fuiouProperties.getReturnUrl()).append("</BACKURL>");
//			sbFm.append("<HOMEURL>").append(fyPayInfo.getPage_notify_url()).append("</HOMEURL>");
//			sbFm.append("<REURL>").append(fyPayInfo.getPage_notify_url_err()).append("</REURL>");
//			sbFm.append("<SIGNTP>").append("md5").append("</SIGNTP>");
//			sbFm.append("<SIGN>").append(signStr).append("</SIGN>");
//			sbFm.append("</ORDER>");
//			log.info("app pay fm:"+sbFm.toString());
//			String xmlFm = DESCoderFUIOU.desEncrypt(sbFm.toString(), DESCoderFUIOU.getKeyLength8(fuiouProperties.getMd5Key()));
//			log.info("app pay xml 签名结果："+xmlFm);
//
//			resMap.put("req_url", fuiouProperties.getPayUrl());
//			resMap.put("ENCTP", fuiouProperties.getEnctp());
//			resMap.put("VERSION", fuiouProperties.getVersion());
//			resMap.put("MCHNTCD", fyPayInfo.getMchnt_cd());
//			//resMap.put("FM", xmlFm.replace("+","%2B"));
//			resMap.put("FM", xmlFm);
//
//			//查询用户账户信息
//			SiteUserAccount siteUserAccount = new SiteUserAccount();
//			SiteUserAccountExample example = new SiteUserAccountExample();
//			example.createCriteria().andUserIdEqualTo(userId);
//			List<SiteUserAccount> userAccountList =  siteUserAccountMapper.selectByExample(example);
//			if (userAccountList == null || userAccountList.size() == 0){//无用户账户记录
//				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
//				resMap.put("result_info", "无用户账户信息");
//				return resMap;
//			}
//
//			//插入充值记录信息 设置状态为充值中
//			SiteUserRecharge siteUserRecharge = getSiteUserRecharge(new SiteUserBuy(),siteUser,siteUserAccount);
//			if (siteUserRecharge == null){
//				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
//				resMap.put("result_info", "用户信息不全");
//				return resMap;
//			}
//			siteUserRechargeMapper.insertSelective(siteUserRecharge);
//		}catch (Exception e){
//			log.info("充值失败");
//		}
//		return resMap;
//	}
//
//	/**
//	 * app 充值失败
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping(value = "/rechargeFailure")
//	public ModelAndView rechargeFailure(HttpServletRequest request) {
//		return new ModelAndView("/app/apphtml/rechargeFailed");
//	}
//
//	/**
//	 * app 充值成功
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping(value = "/rechargeSuccess")
//	public ModelAndView rechargeSuccess(HttpServletRequest request) {
//		return new ModelAndView("/app/apphtml/rechargeSuccessfully");
//	}
//
//	/**
//	 * h5 充值失败
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping(value = "/h5/rechargeFailure")
//	public ModelAndView rechargeFailureOfHtml(HttpServletRequest request) {
//		return new ModelAndView("/h5/html/rechargeFailed");
//	}
//	
//	/**
//	 * h5 充值成功
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping(value = "/h5/rechargeSuccess")
//	public ModelAndView rechargeSuccessOfHtml(HttpServletRequest request) {
//		
//		ModelAndView mv = new ModelAndView("/h5/html/rechargeSuccessfully");
////		String orderNo = request.getParameter("order_no");
////		if(StringUtils.isNotBlank(orderNo)){
////			SiteUserBuyExample siteUserBuyExample = new SiteUserBuyExample();
////			siteUserBuyExample.createCriteria().andOrderNoEqualTo(orderNo);
////			List<SiteUserBuy> siteUserBuyList = siteUserBuyService.selectByExample(siteUserBuyExample);
////			SiteUserBuy siteUserBuy = new SiteUserBuy();
////			if(siteUserBuyList == null){
////				log.info("支付成功查询订单信息：订单信息不存在，订单号:"+orderNo);
////			}
////			siteUserBuy = siteUserBuyList.get(0);
////			if(siteUserBuy ==null){
////				log.info("支付成功查询订单信息：订单信息不存在，订单号:"+orderNo);
////			}
////			
////			ProductExample productExample = new ProductExample();
////			productExample.createCriteria().andProductIdEqualTo(siteUserBuy.getProductId());
////			List<Product> productList = productService.selectByExample(productExample);
////			if(productList == null){
////				log.info("支付成功查询订单信息：产品信息不存在，订单号:"+orderNo+",产品id:"+siteUserBuy.getProductId());
////			}
////			
////			Product product = new Product();
////			product = productList.get(0);
////			
////			//总计收益率
////			BigDecimal totalRate = siteUserBuy.getRate();
////			if(siteUserBuy.getAddRate() != null){
////				totalRate = totalRate.add(siteUserBuy.getAddRate());
////			}
////			//计算收益
////			BigDecimal returnAmount = BigDecimal.ZERO;
////			int totalDays = HJBUT.daysBetween(siteUserBuy.getInterestDate(), siteUserBuy.getCashReturnDate());
////			returnAmount = HJBUT.getInterest(siteUserBuy.getAmount(), totalRate, totalDays);
////			returnAmount = returnAmount.add(siteUserBuy.getAmount());
////			
////			mv.addObject("bidMsg", "恭喜您成功购买"+product.getProductName()+siteUserBuy.getAmount()+"元");
////			mv.addObject("bidDate", HJBUT.currentTime());
////			mv.addObject("interestMsg", "预计"+siteUserBuy.getInterestDate()+"开始计息");
////			mv.addObject("incomeMsg", "预计"+siteUserBuy.getCashReturnDate()+"收益到账，预计收益"+returnAmount+"元");
////		}
//		return mv;
//	}
//
//	/**
//	 * 充值完成回调接口
//	 *
//	 * @param req
//	 * @param resp
//	 */
//	@RequestMapping("/notify")
//	@ResponseBody
//	public void rechargeNotify(HttpServletRequest req, HttpServletResponse resp) {
//		log.info("APP 充值回调成功:" + System.currentTimeMillis());
//		resp.setContentType("text/html");
//		resp.setCharacterEncoding("UTF-8");
//		try {
//			log.info("app pay notify_url res:***************************************** begin");
//			log.info("VERSION:"+req.getParameter("VERSION"));
//			log.info("TYPE:"+req.getParameter("TYPE"));
//			log.info("RESPONSECODE:"+req.getParameter("RESPONSECODE"));
//			log.info("RESPONSEMSG:"+req.getParameter("RESPONSEMSG"));
//			log.info("MCHNTCD:"+req.getParameter("MCHNTCD"));
//			log.info("MCHNTORDERID:"+req.getParameter("MCHNTORDERID"));
//			log.info("ORDERID:"+req.getParameter("ORDERID"));
//			log.info("BANKCARD:"+req.getParameter("BANKCARD"));
//			log.info("AMT:"+req.getParameter("AMT"));
//			log.info("SIGN:"+req.getParameter("SIGN"));
//			log.info("app pay notify_url res:***************************************** end");
//
//			FyPayReturnInfo fyPayReturnInfo = new FyPayReturnInfo();
//			fyPayReturnInfo.setMchnt_cd(req.getParameter("MCHNTCD"));
//			fyPayReturnInfo.setOrder_id(req.getParameter("MCHNTORDERID"));
//			fyPayReturnInfo.setOrder_amt(req.getParameter("AMT"));
//			fyPayReturnInfo.setOrder_pay_code(req.getParameter("RESPONSECODE"));
//			fyPayReturnInfo.setOrder_pay_msg(req.getParameter("RESPONSEMSG"));
//			fyPayReturnInfo.setFy_ssn(req.getParameter("ORDERID"));
//			fyPayReturnInfo.setCard_no(req.getParameter("BANKCARD"));
//			fyPayReturnInfo.setOrder_pay_error(req.getParameter("RESPONSEMSG"));
//			fyPayReturnInfo.setApp_pay_type(req.getParameter("TYPE"));
//			fyPayReturnInfo.setApp_pay_version(req.getParameter("VERSION"));
//			fyPayReturnInfo.setApp_sign(req.getParameter("SIGN"));
//
//			StringBuffer signStr = new StringBuffer();
//			signStr.append(fyPayReturnInfo.getApp_pay_type()).append("|");
//			signStr.append(fyPayReturnInfo.getApp_pay_version()).append("|");
//			signStr.append(fyPayReturnInfo.getOrder_pay_code()).append("|");
//			signStr.append(fyPayReturnInfo.getMchnt_cd()).append("|");
//			signStr.append(fyPayReturnInfo.getOrder_id()).append("|");
//			signStr.append(fyPayReturnInfo.getFy_ssn()).append("|");
//			signStr.append(fyPayReturnInfo.getOrder_amt()).append("|");
//			signStr.append(fyPayReturnInfo.getCard_no()).append("|");
//			signStr.append(fuiouProperties.getMd5Key());
//
//			String sign = MD5.MD5Encode(signStr.toString());
//			if(!sign.equals(fyPayReturnInfo.getApp_sign())){
//				log.info("App充值 富友网关支付异步通知验签失败");
//				resp.getWriter().write("验签失败~");
//				return;
//			}
//
//			// 验签通过后修改金额，系统以元为单位，富友返回以分为单位
//			BigDecimal temp = new BigDecimal(fyPayReturnInfo.getOrder_amt());
//			fyPayReturnInfo.setOrder_amt(String.valueOf(temp.divide(new BigDecimal(100))));
//
//			Map<String, Object> result = fyRechargeService.rechargeNotify(fyPayReturnInfo);
//			if (result.get("result_code") != null && MapUtil.INTF_ERR_CODE.equals(String.valueOf(result.get("result_code")))){
//				log.info("App充值 支付异步通知数据接收处理失败"+result.get("result_info"));
//				resp.getWriter().write("支付失败~");
//				return;
//			}
//			log.info("App充值 富友订单返回的流水号fy_ssn"+fyPayReturnInfo.getFy_ssn());
//			log.info("App充值 支付异步通知数据接收处理成功");
//			if (!"0000".equals(fyPayReturnInfo.getOrder_pay_code())) { // 该订单未支付成功
//				log.info("App充值 富友订单支付失败");
//				resp.getWriter().write("支付失败~");
//				return;
//			}
//			resp.getWriter().write("支付成功~");
//		} catch (Exception e) {
//			log.info("App充值 支付回调处理异常"+e);
//		}
//
//	}
//
//	/**
//	 * 充值查询
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping("/rechargeQuery")
//	@ResponseBody
//	@Transactional
//	public Map<String, Object> rechargeQuery(HttpServletRequest request) {
//		Map<String, Object> resMap = new HashMap<String, Object>();
//		try {
//			//1.获取充值记录
//			SiteUserRechargeExample1 example = new SiteUserRechargeExample1();
//			example.createCriteria().andStatusEqualTo(1).andOrderIdEqualTo("150269127554130381");
//			List<SiteUserRecharge> siteUserRechargeList = siteUserRechargeMapper.selectByExample(example);
//			if (siteUserRechargeList == null || siteUserRechargeList.size() ==0){
//				log.info("未查到处理中的充值记录");
//				return null;
//			}
//			for (SiteUserRecharge siteUserRecharge:siteUserRechargeList){
//				fyRechargeService.rechargeQuery(siteUserRecharge);
//			}
//		}catch (Exception e){
//			log.info("充值查询失败");
//		}
//		return resMap;
//	}
//
//	private SiteUserRecharge getSiteUserRecharge(SiteUserBuy siteUserBuy,SiteUser siteUser,SiteUserAccount siteUserAccount){
//		SiteUserRecharge siteUserRecharge = new SiteUserRecharge();
//		siteUserRecharge.setOrderId(siteUserBuy.getOrderNo());
//		siteUserRecharge.setUserId(siteUserBuy.getUserId());
//		siteUserRecharge.setAmount(siteUserBuy.getAmount());
//		siteUserRecharge.setInitialAmount(siteUserAccount.getTotalRecharge());
//		siteUserRecharge.setFinalAmount(siteUserBuy.getAmount().add(siteUserAccount.getTotalRecharge()));
//		siteUserRecharge.setProductId(siteUserBuy.getProductId());
//		siteUserRecharge.setInfo("用户："+siteUserBuy.getUserId()+" 购买产品："+siteUserBuy.getProductId()+" 金额："+siteUserBuy.getAmount()+" 元");
//		siteUserRecharge.setStatus(0);
//		siteUserRecharge.setCreateTime(new Date());
//		siteUserRecharge.setType(1);
//		siteUserRecharge.setBankCard(siteUser.getBankCardNo());
//		return siteUserRecharge;
//	}
//
//}
